<template>
  <div id="app">
    <div class="logic-flow-view">
      <long-flowlong-designe ref="designerRef" :value="flowData" @on-save="handleSave" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import demoData from '../public/data.json'
import { ElMessage } from 'element-plus'

const designerRef = ref()

const flowData = window.localStorage.getItem('LFDATA') ? JSON.parse(window.localStorage.getItem('LFDATA')!) : demoData

const isIFrame = window.parent !== window

onMounted(() => {
  initMessageListener()
})

const initMessageListener = () => {
  if (isIFrame) {
    window.addEventListener('message', (e) => {
      if (e.data && ['in', 'out'].includes(e.data.type)) {
        // 收到消息，要回复一下
        if (window.parent) {
          window.parent.postMessage(
            {
              success: true,
              type: 'in' // 接收到消息in,传消息out
            },
            '*'
          )
        }
        if (e.data.json) {
          designerRef.value.importJson(e.data.json)
        } else if (e.data.xml) {
          designerRef.value.importXml(e.data.xml)
        }
      }
    })
  }
}

const handleSave = (data: any) => {
  if (isIFrame) {
    window.parent.postMessage(
      {
        success: true,
        type: 'out',
        json: JSON.stringify(data.json),
        xml: data.xml
      },
      '*'
    )
  } else {
    ElMessage.success('保存本地成功')
    window.localStorage.setItem('LFDATA', JSON.stringify(data.json))
    if (data.json.name && data.json.displayName) {
      // 以一定规则存入，方便选择导入
      window.localStorage.setItem(`LFDATA###${data.json.name}###${data.json.displayName}`, JSON.stringify(data.json))
      // 触发更新
      if (designerRef.value.refreshLfData === 1) {
        designerRef.value.refreshLfData = 2
      } else {
        designerRef.value.refreshLfData = 1
      }
    }
  }
}
</script>

<style scoped lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
.m-button-group-wrap {
  width: 100%;
  position: fixed;
  left: 100px;
  bottom: 0;
  z-index: 9999;
}

.logic-flow-view {
  height: 100vh;
  position: relative;
}
</style>
